package com.ruoyi.yyq.controller;

import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.security.annotation.InnerAuth;
import com.ruoyi.user.api.RemoteCarUserService;
import com.ruoyi.user.api.domain.CarUser;
import com.ruoyi.yyq.domain.vo.CarEvaluationVo;
import com.ruoyi.yyq.domain.vo.EvaluationCar;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.yyq.domain.CarEvaluation;
import com.ruoyi.yyq.service.ICarEvaluationService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 评价Controller
 *
 * @author 尹永青
 * @date 2025-05-10
 */
@RestController
@RequestMapping("/evaluation")
@CrossOrigin
public class CarEvaluationController extends BaseController {
    @Autowired
    private ICarEvaluationService carEvaluationService;
    @Resource
    private ElasticsearchRestTemplate restTemplate;
    @Resource
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private RemoteCarUserService remoteCarUserService;

    private static final String INDEX = "car_evaluation";

    /**
     * 查询评价列表
     */
    @RequiresPermissions("yyq:evaluation:list")
    @GetMapping("/list")
    public TableDataInfo list(CarEvaluation carEvaluation) {
        startPage();
        carEvaluation.setDeleted(0L);
        List<CarEvaluation> list = carEvaluationService.selectCarEvaluationList(carEvaluation);
        return getDataTable(list);
    }

    @RequiresPermissions("yyq:evaluation:list")
    @GetMapping("/listByMid/{mid}")
    public AjaxResult listByMid(@PathVariable("mid") Long mid) {
        // 构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        queryBuilder.withQuery(QueryBuilders.boolQuery()
                .must(QueryBuilders.termQuery("deleted", 0L))
                .must(QueryBuilders.termQuery("status", 2L))
                .must(QueryBuilders.termQuery("mid", mid))
        );
        // 执行查询
        SearchHits<EvaluationCar> searchHits = restTemplate.search(queryBuilder.build()
                , EvaluationCar.class
                , IndexCoordinates.of(INDEX));
        // 提取查询结果
        List<EvaluationCar> evaluations = searchHits.stream()
               .map(SearchHit::getContent)
               .collect(Collectors.toList());
        for (EvaluationCar evaluation : evaluations) {
            Long userId = evaluation.getUser_id();
            CarUser info = remoteCarUserService.getUserInfoById(userId, SecurityConstants.INNER);
            evaluation.setUserName(info.getNickName());
        }
        return AjaxResult.success(evaluations);
    }

    /**
     * 导出评价列表
     */
    @RequiresPermissions("yyq:evaluation:export")
    @Log(title = "评价", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CarEvaluation carEvaluation) {
        List<CarEvaluation> list = carEvaluationService.selectCarEvaluationList(carEvaluation);
        ExcelUtil<CarEvaluation> util = new ExcelUtil<CarEvaluation>(CarEvaluation.class);
        util.exportExcel(response, list, "评价数据");
    }

    /**
     * 获取评价详细信息
     */
    @RequiresPermissions("yyq:evaluation:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(carEvaluationService.selectCarEvaluationById(id));
    }

    /**
     * 新增评价
     */
    @RequiresPermissions("yyq:evaluation:add")
    @Log(title = "评价", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CarEvaluation carEvaluation) {
        carEvaluation.setStatus(1L);
        return toAjax(carEvaluationService.insertCarEvaluation(carEvaluation));
    }

    /**
     * 修改评价
     */
    @RequiresPermissions("yyq:evaluation:edit")
    @Log(title = "评价", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CarEvaluation carEvaluation) {
        return toAjax(carEvaluationService.updateCarEvaluation(carEvaluation));
    }

    /**
     * 删除评价
     */
    @RequiresPermissions("yyq:evaluation:remove")
    @Log(title = "评价", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(carEvaluationService.deleteCarEvaluationByIds(ids));
    }
}
